<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Auth extends CI_Controller {

	function Auth()
	{
		parent::__construct();
		// LOAD LIBRARIES
		$this->load->library(array('encrypt', 'form_validation', 'session'));
		$this->load->library('ion_auth');

		// LOAD HELPERS
		$this->load->helper(array('form'));
	}

	//redirect if needed
	function index()
	{
		if (!$this->ion_auth->logged_in()) {
			//redirect them to the login page
			redirect('admin/auth/login', 'refresh');
		} elseif ($this->ion_auth->is_admin()) {
			//redirect them to the home page because they must be an administrator to view this
			redirect(site_url('admin/gallery'), 'refresh');
		} else {
			redirect(site_url('admin/auth'), 'refresh');
		}
	}

	//log the user in
	function login()
	{
		//validate form input
		$this->form_validation->set_rules('user_name', 'Name', 'trim|required|valid_email');
		$this->form_validation->set_rules('user_pass', 'Password', 'trim|required');
		//check to see if the user is logging in
		if ($this->form_validation->run() == true) { 
			//check for "remember me"
			$remember = (bool) $this->input->post('remember');
			if ($this->ion_auth->login($this->input->post('user_name'), $this->input->post('user_pass'), $remember)) { //if the login is successful
				//redirect them back to the home page
				$this->session->set_flashdata('message', $this->ion_auth->messages());
				redirect(site_url('admin/gallery'), 'refresh');
			} else { //if the login was un-successful
				//redirect them back to the login page
				$this->session->set_flashdata('message', $this->ion_auth->errors());
				redirect('admin/auth', 'refresh'); //use redirects instead of loading views for compatibility with MY_Controller libraries
			}
		} else {  //the user is not logging in so display the login page
			$this->parser->parse("admin/auth.tpl");
		}
	}

	function logout()
	{
		//log the user out
		$logout = $this->ion_auth->logout();

		//redirect them back to the page they came from
		redirect('admin/auth', 'refresh');
	}
}

/* End of file auth.php */
/* Location: ./application/controllers/auth.php */
